//
//  ViewController.swift
//  UnCloudNotes
//
//  Created by Saul Mora on 6/10/14.
//  Copyright (c) 2014 Ray Wenderlich. All rights reserved.
//

import UIKit
import CoreData

//@objc (NotesListViewController)
class NotesListViewController: UITableViewController, NSFetchedResultsControllerDelegate {
	
	/*
	The NSMigratePersistentStoresAutomaticallyOption is what tells Core Data (the NSPersistentStoreCoordinator, actually) to start a migration if the persistent store model isn’t compatible with the current data model. Core Data will handle all the details, from finding the source model to creating the destination store file, and all the steps in between.
	
	The NSInferMappingModelAutomaticallyOption is the other half of what makes a lightweight migration possible. Every migration requires a mapping model. Here’s an analogy: If you’re traveling from a known place on Earth to somewhere unknown, you’ll want a map to tell you where to go. The mapping model is that guide.
	
	It just so happens that Core Data can infer a mapping model in many cases. That is, Core Data can automatically look at the differences in two data models and create a mapping model between them. For entities and attributes that are identical between model versions, this is a straightforward data pass through mapping. For other changes, just follow a few simple rules for Core Data to create a mapping model. In the new model, changes must fit an obvious migration pattern, such as:
	
	1.Deleting entities, attributes or relationships;
	2.Renaming entities, attributes or relationships using the renamingIdentifier;
	3.Adding a new, optional attribute;
	4.Adding a new, required attribute with a default value;
	5.Changing an optional attribute to non-optional and specifying a default value;
	6.Changing a non-optional attribute to optional;
	7.Changing the entity hierarchy;
	8.Adding a new parent entity and moving attributes up or down the hierarchy;
	9.Changing a relationship from to-one to to-many;
	10.Changing a relationship from non-ordered to-many to ordered to-many (and vice versa).
	*/
  lazy var stack : CoreDataStack = CoreDataStack(modelName:"UnCloudNotesDataModel", storeName:"UnCloudNotes",
		options:[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
	)
  
  var _notes : NSFetchedResultsController? = nil
  var notes : NSFetchedResultsController {
    if _notes == nil {
      let request = NSFetchRequest(entityName: "Note")
      request.sortDescriptors = [NSSortDescriptor(key: "dateCreated", ascending: false)]
    
      let notes = NSFetchedResultsController(fetchRequest: request, managedObjectContext: stack.context, sectionNameKeyPath: nil, cacheName: nil)
      notes.delegate = self
      _notes = notes
    }
    return _notes!
  }
  
  override func viewWillAppear(animated: Bool){
    super.viewWillAppear(animated)
    notes.performFetch(nil)
    tableView.reloadData()
  }
  
  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var objects = notes.fetchedObjects
    if let objects = objects
    {
        return objects.count
    }
    return 0
  }
  
  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
		let note = notes.fetchedObjects?[indexPath.row] as? Note
		var identifier = "NoteCell"
		if let image = note?.image {
			identifier = "NoteCellImage"
		}
		
    var cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! NoteTableViewCell;
		cell.note = note
		
    return cell
  }
  
  func controllerWillChangeContent(controller: NSFetchedResultsController) {
    
  }
  
  func controller(controller: NSFetchedResultsController??!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
    switch type
      {
    case .Insert:
      tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic)
    case .Delete:
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    default:
      break
    }
  }
  
  func controllerDidChangeContent(controller: NSFetchedResultsController) {
    
  }
  
  @IBAction
  func unwindToNotesList(segue:UIStoryboardSegue) {
    NSLog("Unwinding to Notes List")
    var error : NSErrorPointer = nil
    if stack.context.hasChanges
    {
      if stack.context.save(error) == false
      {
        print("Error saving \(error)")
      }
    }
  }
  
  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "createNote"
    {
      let context = NSManagedObjectContext(concurrencyType: .ConfinementConcurrencyType)
      context.parentContext = stack.context
      let navController = segue.destinationViewController as! UINavigationController
      let nextViewController = navController.topViewController as! CreateNoteViewController
      nextViewController.managedObjectContext = context
    }
    if segue.identifier == "showNoteDetail" {
      let detailView = segue.destinationViewController as! NoteDetailViewController
        if let selectedIndex = tableView.indexPathForSelectedRow() {
          if let objects = notes.fetchedObjects {
            detailView.note = objects[selectedIndex.row] as? Note
          }
      }
    }
  }
}
